import cv2
import cv
import sys
import cpoo_tools as tools
import numpy as np

image = cv.LoadImage( sys.argv[1] )

# tools.grow_region(image)

# TODO: set radius dynamically
img = cv.CreateImage( cv.GetSize( image ), image.depth, image.nChannels )
img = tools.split_channels( image )

img = tools.array2cv( cv2.GaussianBlur( tools.cv2array( img ), ( 5, 5 ), 5 ) )
entropies = tools.entropy( img[:, img.width / 2:] )

for i in range( 10, -1, -1 ):
    entropies[len( entropies ) - 1 - i] = entropies[len( entropies ) - 2 - i]
    entropies[i] = entropies[i + 1]

# print entropies

diffs = tools.derivative_of_vector( entropies, 1 )
ind_min = diffs.index( min( diffs ) )
ind_max = diffs.index( max( diffs ) )

print "Clipping zone: " + str( ind_max ) + "-" + str( ind_min ) + ", values: " + str( diffs[ind_max] ) + ", " + str( diffs[ind_min] )

# print diffs

clipped = tools.cropImage( image, 0, min( ind_max, ind_min ), image.width, max( ind_max, ind_min ) )
cv.ShowImage( "clipped", clipped )
cv.WaitKey()

regions = cv.CreateImage( cv.GetSize( clipped ), clipped.depth, clipped.nChannels )
tools.grow_regions( clipped )

# cv.WaitKey
